﻿using Cemit.PolyProto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Cemit.NetFramework
{
    /// <summary>自动压入操作帧，提供弹出操作帧和发送操作的接口</summary>
    public class FrameSyncRoom
    {
        public int Remain => frameBuffer.Remain;

        private readonly OperationFrameBuffer frameBuffer;
        private readonly Action<O> sendOperationAction;
        private readonly int gameRoomId;

        public FrameSyncRoom(int gameRoomId, PolySocket gameServer)
        {
            this.gameRoomId = gameRoomId;

            frameBuffer = new OperationFrameBuffer();

            // 监听操作帧数据
            gameServer.AddMessageListener<F>(
                frame => frameBuffer.AddFrame((F)frame));

            sendOperationAction = operation => gameServer.Send(operation);

            //this.sendOperationAction = sendOperationAction;
            //this.frameBuffer = frameBuffer;
        }

        public IEnumerable<string> PopOperationFrame()
        {
            return frameBuffer.ReadFrame();
        }

        public IEnumerable<string> PopOperationFrame(out int index)
        {
            return frameBuffer.ReadFrame(out index);
        }

        public void SendOperation(string operation)
        {
            sendOperationAction.Invoke(new O 
            {
                RoomId = gameRoomId,
                Operation = operation
            });
        }
    }
}
